package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.TeachInfo;
import com.eduadmin.entity.Teacher;
import com.eduadmin.exception.CustomException;
import com.eduadmin.service.ITeachInfoService;
import com.eduadmin.service.ITeacherService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class TeachInfoDataUploadListener extends AnalysisEventListener<TeachInfo> {
    private int count = 1;
    private final ITeachInfoService teachInfoService;
    private final ITeacherService teacherService;

    public TeachInfoDataUploadListener(ITeacherService teacherService, ITeachInfoService teachInfoService) {
        this.teachInfoService = teachInfoService;
        this.teacherService = teacherService;
    }

    List<TeachInfo> list = new ArrayList<>();
    List<String> errors = new ArrayList<>();   //记录错误信息
    Teacher teacherByTeacherIdcard;
    List<TeachInfo> teachInfo;

    @Override
    public void invoke(TeachInfo data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        count++;    //计录 excel表格中的数据行号
        //判断excel表中字段的顺序是否正确  是否选对导入数据文件
        if ((data.getTeacherIdCard().length() == 18) && data.getTeamName().contains(data.getGradeName()) && (data.getTeamName().length() == 9)) {
            //如果teacher表中没有该教师的id信息 不能导入
            teacherByTeacherIdcard = teacherService.getTeacherByTeacherIdcard(data.getTeacherIdCard());
            if (teacherByTeacherIdcard != null && teacherByTeacherIdcard.getTeacherName().equals(data.getTeacherName())) {
                teachInfo = teachInfoService.getTeachInfo(data);    //判断数据库中是否有相同的任教记录
                if (teachInfo.size() == 0) {  //判断任教信息不存在 存入数据库
                    list.clear();
                    list.add(data);
                    saveData();
                } else {
                    //任教信息存在
                    errors.add("Excel 数据表中第 " + count + " 行的任教信息已经在数据库中，不能导入！");
                }
            } else {
                //身份证号不在教师表中或者身份证和名字不一致
                errors.add("Excel 数据表中第 " + count + " 行的信息不在教师表中或者身份证和名字不一致，不能导入！");
            }
        } else {
            //可能导入的excel文件 字段顺序错误
            errors.add("Excel 数据表中第 " + count + " 行信息数据错误，不能导入！");
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
        //如果有重复行数据 抛异常提醒用户
        if (errors.size() > 0) {
            throw new CustomException("/adminindex", " ", errors);
        }
    }

    /**
     * 存储数据库
     */
    private void saveData() {
        log.info("第 {}行 数据，开始存储数据库！", count);
        if (!CollectionUtils.isEmpty(list)) {
            teachInfoService.addTeachInfos(list);
        }
        log.info("存储数据库成功！");
    }


}
